<template>
	<view class="page-content">
		<view class="page-top">
			<!-- 标题栏和状态栏占位符 -->
			<view class="titleNview-placing"></view>
			<!-- 搜索 -->
			<w-sel-search :itemArr="objdata" :obj="selobj" @subItemClick="subItemClick"  :is_r_i="true" @tosearch="tosearch" @toadd="toadd"></w-sel-search>
		</view>
		<scroll-view class="page-body" :scroll-top="scrollTop" scroll-y="true"> <!-- @scrolltolower="loadmore()" -->
			<view class="body-box">
				<!--群聊 置顶-->
				<chat-list :list="userAddConversationLists" @tomsg="tomsg" :isPinned="true"></chat-list>
				<!--群聊 不置顶-->
				<chat-list :list="userAddConversationLists" @tomsg="tomsg"></chat-list>
			</view>
			<view class="body-box2">
				<!--单聊-->
				<chat-list :list="userAddConversationList" @tomsg="tomsg" type="single" :isPinned="true"></chat-list>
				<chat-list :list="userAddConversationList" @tomsg="tomsg" type="single"></chat-list>
			</view>
			<!-- 上拉加载 -->
			<view class="det-con-more">
				<load-more :loadmore="load_more1"></load-more>
			</view>
			<view v-if="!userAddConversationLists.length && !userAddConversationList.length" class="empty">
				<image src="../../static/empty/no_data.png" mode=""></image>
				<view class="empty-str">暂时没有消息</view>
			</view>
			<!--无数据-->
		</scroll-view>
	</view>
</template>

<script>
	import wSelSearch from '@/components/w-sel-logo/w-sel-search.vue'; //品牌logo
	import chatList from '@/components/w-chat/chat-list.vue'; //聊天组件
	import loadMore from '@/components/uni-load-more/load-more.vue';
	import {
			mapGetters,
			mapActions,
			mapState
		} from 'vuex';
	import TIM from 'tim-js-sdk';
	import store from '@/store';
	import { getCompanyLists,getBannerLists,orderCounts,getUserCompanys,getUserInfos,getCompanyUserInfos,getMailLists,tencentImAuths } from '@/common/api.js';
	export default {
		components: {
			wSelSearch,
			chatList,loadMore
		},
		data() {
			return {
				scrollTop: 0,
				noData: false,
				load_more1: '', //下拉加载文字
				load_sta: false, //是否是加载状态
				currentSubIndex:0,//选中品牌序号
				selobj:{
					logo_img: "",
					title: "",
					id:0,
					statu: false
				},
				objdata: [],
				params:{
					company_id:'',
					uid:0
				},
				is_change:false,
				contact:[], //通讯录
				userAddConversationList:[],
				userAddConversationLists:[]
			}
		},
		watch: {
			companyInfo(val,old) {
				this.getcompanyInfo(val,old)
			},
			isSDKReady(val) {
				//isSDKReady == true 请求会话列表
				if (val) {
					this.getConversationList()
				}
			},
			conversationList(val) {
				this.getUserInfosss(val);
				this.getUserInfoss(val);
			}
			
		},
		computed: {
			...mapGetters(['userInfo', 'userSig','companyInfo','selIndex','contactList','companyRole','userRole']),
			...mapState({
				isLogin: state => state.isLogin,
				isSDKReady: state => state.isSDKReady,
				conversationList: state => state.conversationList,
			}),
		},
		onShow() {
			this.params.company_id = this.companyInfo.id;
			this.getData();
			if (this.isSDKReady) {
				this.getConversationList();
			}
			//uni.removeTabBarBadge(OBJECT)
		},
		methods:{
			...mapActions('user',['setCompanyInfo','setSelIndex','setUserInfo','setContactList','setUserSig','setCompanyRole','setUserRole']),
			async getData(){ //初始化-公司数据
				let resdata1 = await getUserCompanys(); // 获取公司信息
				let currentSubIndex = 0
				if(!!this.selIndex){
					currentSubIndex = this.selIndex;
				}else{
					this.setSelIndex(currentSubIndex);
				}
				this.objdata = resdata1.data;
				this.selobj = resdata1.data[currentSubIndex];
			},
			subItemClick(index){ //选择品牌
				this.currentSubIndex = index;
				this.selobj = this.objdata[this.currentSubIndex];
				this.setSelIndex(index)
				this.getData2()
			},
			async getData2() { //选择品牌 - 初始化 - 公司数据
			console.log('切换品牌-初始化-公司数据')
			    uni.showLoading({
			    	mask: true
			    })
			    // 切换公司-获取公司信息
				let resdata1 = await getUserCompanys(); 
				let currentSubIndex = 0
				if(!!this.selIndex){
					currentSubIndex = this.selIndex;
				}else{
					this.setSelIndex(currentSubIndex); //设置缓存
				}
				this.objdata = resdata1.data;
				this.selobj = resdata1.data[currentSubIndex];
				//获取用户信息
				let resdata2 = await getUserInfos({company_id: this.selobj.id}); 
				// 获取公司通讯录
				let params1 = { company_id:this.selobj.id,type:1}
				let params2 = { company_id:this.selobj.id,type:2}
				let resdata3 = await getMailLists(params1);
				let resdata4 = await getMailLists(params2);
				this.contact = [...resdata3.data, ...resdata4.data]
				//设置缓存 公司-用户-通讯录
				this.setCompanyInfo(this.selobj)
				this.setUserInfo(resdata2.data);
				this.setContactList(this.contact);
				uni.hideLoading()
			},
			//根据消息列表请求聊天对象的用户信息 并完成数据拼接
			getUserInfoss(conversationList) {
				let _self = this;
				this.userAddConversationList = []
				if(!!this.contactList){
					this.contact = this.contactList;
					for (let i in conversationList) {
						let item = conversationList[i]
						if (item.type === 'C2C') {
							let obj = {};
							obj.unreadCount = item.unreadCount;
							obj.conversation = item;
							if(_self.contact && _self.contact.length>0){
								_self.contact.forEach(ite=>{
									if(item.toAccount === (_self.companyInfo.id + ':' + ite.uid)){
										obj.user = ite;
										_self.userAddConversationList.push(obj);
										_self.$forceUpdate();
									}														  
								})
							}
						}
					}
				}
				//console.log(11111,this.userAddConversationList)
			},
			//根据消息列表请求聊天对象的用户信息 并完成数据拼接
			getUserInfosss(conversationList) {
				let _self = this;
				let userAddConversationLists = []
				if(!!this.contactList){
					this.contact = this.contactList;
					for (let i in conversationList) {
						let item = conversationList[i]
						if(item.type === 'GROUP' && item.subType === 'Private'){
							let obj = {
								user:{},
								users:[]
							};
							obj.unreadCount = item.unreadCount;
							obj.conversation = item;
							//获取群列表
							let promise2 = _self.tim.getGroupMemberList({ groupID: item.toAccount, count: 9, offset:0 }); // 从0开始拉取30个群成员
							promise2.then(function(imResponse2) {
							  //console.log('成员列表：',imResponse2.data.memberList,_self.contact); // 群成员列表
							  if(_self.contact && _self.contact.length>0){
								  _self.contact.forEach(ite=>{
									  if(item.lastMessage.fromAccount === (_self.companyInfo.id + ':' + ite.uid)){
										  obj.user = ite;
									  }
									  if(imResponse2.data.memberList && imResponse2.data.memberList.length>0){
										  imResponse2.data.memberList.forEach(i=>{
											  if(i.userID === (_self.companyInfo.id + ':' + ite.uid)){
												  obj.users.push(ite)
											  }
										  })
									  }
								  })
								  userAddConversationLists.push(obj)
							  }
							}).catch(function(imError) {
							  console.log('getGroupMemberList error:', imError);
							});	
						}
					}
				}
				_self.userAddConversationLists = userAddConversationLists;
				console.log(999,_self.userAddConversationLists)
				_self.$forceUpdate();
				this.is_change = false;
			},
			//获取消息列表
			getConversationList() {
				// 拉取会话列表
				let promise = this.tim.getConversationList();
				promise.then((res) => {
					//console.log(222333, res)
					let conversationList = res.data.conversationList; // 会话列表，用该列表覆盖原有的会话列表
					if (conversationList.length) {
						//将返回的会话列表拼接上 用户的基本资料
						//说明：如果已经将用户信息 提交到tim服务端了 就不需要再次拼接
						this.$store.commit("updateConversationList", conversationList);
					}
				}).catch((err) => {
					console.log('getConversationList error:', err); // 获取会话列表失败的相关信息
				});
			},
			//跳转聊天界面
			tomsg(id,name,type){
				if(type === 'C2C'){
					this.$store.commit('createConversationActive', id)
					uni.navigateTo({
						url: `/pages/message/messageInfo?id=${id}&name=${name}&type=${type}`
					})				
				}else if(type === 'GROUP'){
					this.$store.commit('createConversationActives', id)
					uni.navigateTo({
						url: `/pages/message/messageInfo?id=${id}&name=${name}&type=GROUP`
					})
				}
			},
			tosearch(){
				uni.navigateTo({
					url:`/pages/message/messageSearch?pageType=search`
				})
			},
			toadd(){
				uni.navigateTo({
					url:`/pages/contact/contactAdd?pageType=createGroup`
				})
			},
			getcompanyInfo(val,old){
				let _self = this;
				this.is_change = true;
				console.log(2222,val,old)
				//获取公司权限
				this.getCompanyRole();
				
				//退出登录
				let promise = _self.tim.logout();
				promise.then(function(imResponse) {
				  console.log('退出登录：',imResponse.data); // 登出成功
				  //获取im userSig
				  tencentImAuths({company_id:val.id}).then(res4 => {
				  	if (res4.code === 2000) {
				  		_self.setUserSig(res4.data.user_sig)
				  		//console.log('timlogin')
				  		//tim登录
				  		let promise2 = _self.tim.login({
				  			userID:val.id + ':' + _self.userInfo.uid+'',
				  			userSig: res4.data.user_sig
				  		});
				  		let userInfo = {
				  			userID:val.id + ':' + _self.userInfo.uid+'',
				  			userSig: res4.data.user_sig
				  		};
				  		promise2.then((res5) => {
				  			console.log('登录成功', res5)
				  			//登录成功后 更新登录状态
				  			//_self.$store.commit("toggleIsLogin", true);
				  			//自己平台的用户基础信息
				  			uni.setStorageSync('userInfo', JSON.stringify(userInfo))
				  			//tim 返回的用户信息
				  			uni.setStorageSync('userTIMInfo', JSON.stringify(res5.data))
				  			
				  		}).catch((err) => {
				  			console.log('login error:', err); // 登录失败的相关信息
				  		});
				  	}
				  })
				}).catch(function(imError) {
				  console.log('logout error:', imError);
				  tencentImAuths({company_id:val.id}).then(res4 => {
				  	if (res4.code === 2000) {
				  		_self.setUserSig(res4.data.user_sig)
				  		//console.log('timlogin')
				  		//tim登录
				  		let promise2 = _self.tim.login({
				  			userID:val.id + ':' + _self.userInfo.uid+'',
				  			userSig: res4.data.user_sig
				  		});
				  		let userInfo = {
				  			userID:val.id + ':' + _self.userInfo.uid+'',
				  			userSig: res4.data.user_sig
				  		};
				  		promise2.then((res5) => {
				  			console.log('登录成功', res5)
				  			//登录成功后 更新登录状态
				  			//_self.$store.commit("toggleIsLogin", true);
				  			//自己平台的用户基础信息
				  			uni.setStorageSync('userInfo', JSON.stringify(userInfo))
				  			//tim 返回的用户信息
				  			uni.setStorageSync('userTIMInfo', JSON.stringify(res5.data))
				  			
				  		}).catch((err) => {
				  			console.warn('login error:', err); // 登录失败的相关信息
				  		});
				  	}
				  })
				});
			},
			getCompanyRole(){
				console.log('获取公司权限')
				let companyRole = {
					bas_role:true,
					team_role:true,
					news_role:true,
					pop_role:false,
					pro_role:false,
					prop_role:false,
				}
				let userRole = {
					proStatu:false, //产品属性设置-1
					popStatu:false, //POP编码设置-2
					propStatu:false, //道具编码设置-3
					textureStatu:false, //POP材质设置-4
					quotationStatu:false, //供应商报价单-5
					
					memberStatu:false, //成员管理-6
					groupStatu:false, //组别管理-7
					powerStatu:false, //权限管理-8
					
					newsStatu:false, //新闻管理-9
					noticeStatu:false, //公告&通知管理-10
					dynamicStatu:false, //动态管理-11
					
					proOrderStatu:false, //POP画册管理-12
					
					popOrderStatu:false , //POP下单管理-13
					countStatu1:false , //数据统计功能-14
					
					propOrderStatu:false , //POP下单管理-15
					countStatu2:false , //数据统计功能-16
				}
				let role_arr = []
				if(!!this.userInfo){
					if(this.userInfo.role_arr && this.userInfo.role_arr.length>0){
						role_arr = this.userInfo.role_arr
					}
				}
				if(!!this.companyInfo){
					if(this.companyInfo.roleArr && this.companyInfo.roleArr.length>0){
						this.companyInfo.roleArr.forEach(item=>{
							if(item === '1'){
								companyRole.bas_role = true;
								if(this.userInfo.type === 0){
									userRole.proStatu = true;
									userRole.popStatu = true;
									userRole.powerStatu = true;
									userRole.textureStatu = true;
									userRole.quotationStatu = true;
								}else if(this.userInfo.type === 1){
									role_arr.forEach(ite=>{
										if(parseInt(ite) === 1){
											userRole.proStatu = true;
										}else if(parseInt(ite) === 2){
											userRole.popStatu = true;
										}else if(parseInt(ite) === 3){
											userRole.powerStatu = true;
										}else if(parseInt(ite) === 4){
											userRole.textureStatu = true;
										}else if(parseInt(ite) === 5){
											userRole.quotationStatu = true;
										}
									})
								}
							}else if(item === '2'){
								companyRole.team_role = true;
								if(this.userInfo.type === 0){
									userRole.memberStatu = true;
									userRole.groupStatu = true;
									userRole.propStatu = true;
								}else if(this.userInfo.type === 1){
									role_arr.forEach(ite=>{
										if(parseInt(ite) === 6){
											userRole.memberStatu = true;
										}else if(parseInt(ite) === 7){
											userRole.groupStatu = true;
										}else if(parseInt(ite) === 8){
											userRole.propStatu = true;
										}
									})
								}
							}else if(item === '3'){
								companyRole.news_role = true;
								if(this.userInfo.type === 0){
									userRole.newsStatu = true;
									userRole.noticeStatu = true;
									userRole.dynamicStatu = true;
								}else if(this.userInfo.type === 1){
									role_arr.forEach(ite=>{
										if(parseInt(ite) === 9){
											userRole.newsStatu = true;
										}else if(parseInt(ite) === 10){
											userRole.noticeStatu = true;
										}else if(parseInt(ite) === 11){
											userRole.dynamicStatu = true;
										}
									})
								}
							}else if(item === '4'){
								companyRole.pro_role = true;
								if(this.userInfo.type === 0){
									userRole.proOrderStatu = true;
								}else if(this.userInfo.type === 1){
									role_arr.forEach(ite=>{
										if(parseInt(ite) === 12){
											userRole.proOrderStatu = true;
										}
									})
								}
							}else if(item === '5'){
								companyRole.pop_role = true;
								if(this.userInfo.type === 0){
									userRole.popOrderStatu = true;
									userRole.countStatu1 = true;
								}else if(this.userInfo.type === 1){
									role_arr.forEach(ite=>{
										if(parseInt(ite) === 13){
											userRole.popOrderStatu = true;
										}else if(parseInt(ite) === 14 ){
											userRole.countStatu1 = true;
										}
									})
								}
							}else if(item === '6'){
								companyRole.prop_role = true;
								if(this.userInfo.type === 0){
									userRole.propOrderStatu = true;
									userRole.countStatu2 = true;
								}else if(this.userInfo.type === 1){
									role_arr.forEach(ite=>{
										if(parseInt(ite) === 15){
											userRole.propOrderStatu = true;
										}else if(parseInt(ite) === 16){
											userRole.countStatu2 = true;
										}
									})
								}
							}
						})
					}
				}
				this.setCompanyRole(companyRole)
				this.setUserRole(userRole)
			},
		}
	}
</script>

<style lang="scss">
	.empty{
		display: flex;
		justify-content: center;
		flex-wrap: wrap;
		margin-top: 280rpx;
		
		image {
			width: 374rpx;
			height: 295rpx;
		}
		.empty-str {
			text-align: center;
			margin: 0 auto;
			width: 750rpx;
			height: 88rpx;
			font-size: 28rpx;
			font-family: PingFangSC-Regular, PingFang SC;
			font-weight: 400;
			color: #999999;
		}
	}
	.titleNview-placing {
		height: var(--status-bar-height);
		box-sizing: content-box;
		background: $uni-bg-color;
		display: block;
		position: sticky;
		top: 0rpx;
		z-index: 9999;
		overflow: hidden
	}
	.page-content {
		display: flex;
		flex-direction: column;
		height: 100%;

		.page-body {
			height: calc(100% - 90rpx - var(--status-bar-height));

			.body-box {
				padding: 0 30rpx;
				display: flex;
				flex-direction: column;
				background: $uni-bg-color-grey;
			}
			.body-box2 {
				padding: 0 30rpx;
				display: flex;
				flex-direction: column;
				background: $uni-bg-color;
			}
		}

		.page-top {
			display: flex;
			flex-direction: column;
			box-sizing: content-box;
			background: $uni-bg-color;
			display: block;
			position: sticky;
			top: 0rpx;
			z-index: 9999;
		}
	}
</style>
